package com.example.projectmanagement.controller.study;

import com.example.projectmanagement.dto.study.StudyPointsTransactionDto;
import com.example.projectmanagement.model.study.StudyPointsTransaction;
import com.example.projectmanagement.model.User;
import com.example.projectmanagement.service.study.StudyPointsService;
import com.example.projectmanagement.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/study/points")
@CrossOrigin
public class StudyPointsController {

    @Autowired
    private StudyPointsService pointsService;
    
    @Autowired
    private UserService userService;

    /**
     * 获取用户积分交易记录（分页）
     */
    @GetMapping
    public ResponseEntity<Page<StudyPointsTransactionDto>> getUserPointsTransactions(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        Pageable pageable = PageRequest.of(page, size);
        Page<StudyPointsTransaction> transactions = pointsService.getUserPointsTransactions(userOpt.get(), pageable);
        
        // 转换为 DTO
        Page<StudyPointsTransactionDto> transactionDtos = transactions.map(this::convertToTransactionDto);
        
        return ResponseEntity.ok(transactionDtos);
    }

    /**
     * 获取用户最近的积分交易记录
     */
    @GetMapping("/recent")
    public ResponseEntity<Page<StudyPointsTransactionDto>> getRecentTransactions(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        Pageable pageable = PageRequest.of(page, size);
        Page<StudyPointsTransaction> transactions = pointsService.getRecentTransactions(userOpt.get(), pageable);
        
        // 转换为 DTO
        Page<StudyPointsTransactionDto> transactionDtos = transactions.map(this::convertToTransactionDto);
        
        return ResponseEntity.ok(transactionDtos);
    }

    /**
     * 获取用户总积分
     */
    @GetMapping("/total")
    public ResponseEntity<Integer> getUserTotalPoints() {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        Integer totalPoints = pointsService.getUserTotalPoints(userOpt.get());
        return ResponseEntity.ok(totalPoints);
    }

    /**
     * 用户观看视频获得积分
     */
    @PostMapping("/earn/watch-video")
    public ResponseEntity<StudyPointsTransaction> earnPointsForWatchingVideo(
            @RequestParam Integer minutesWatched,
            @RequestParam Long lessonId) {
        
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        StudyPointsTransaction transaction = pointsService.earnPointsForWatchingVideo(userOpt.get(), minutesWatched, lessonId);
        return ResponseEntity.ok(transaction);
    }

    /**
     * 用户完成课程获得积分
     */
    @PostMapping("/earn/complete-course")
    public ResponseEntity<StudyPointsTransaction> earnPointsForCompletingCourse(@RequestParam Long courseId) {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        StudyPointsTransaction transaction = pointsService.earnPointsForCompletingCourse(userOpt.get(), courseId);
        return ResponseEntity.ok(transaction);
    }

    /**
     * 用户提问获得积分
     */
    @PostMapping("/earn/ask-question")
    public ResponseEntity<StudyPointsTransaction> earnPointsForAskingQuestion(@RequestParam Long questionId) {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        StudyPointsTransaction transaction = pointsService.earnPointsForAskingQuestion(userOpt.get(), questionId);
        return ResponseEntity.ok(transaction);
    }

    /**
     * 用户回答被采纳获得积分
     */
    @PostMapping("/earn/accepted-answer")
    public ResponseEntity<StudyPointsTransaction> earnPointsForAcceptedAnswer(@RequestParam Long answerId) {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        StudyPointsTransaction transaction = pointsService.earnPointsForAcceptedAnswer(userOpt.get(), answerId);
        return ResponseEntity.ok(transaction);
    }

    /**
     * 用户每日签到获得积分
     */
    @PostMapping("/earn/daily-checkin")
    public ResponseEntity<StudyPointsTransaction> earnPointsForDailyCheckIn() {
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> userOpt = userService.getUserById(currentUserId);
        if (!userOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        StudyPointsTransaction transaction = pointsService.earnPointsForDailyCheckIn(userOpt.get());
        return ResponseEntity.ok(transaction);
    }

    /**
     * 获取所有学生列表（供管理员和讲师查看）
     */
    @GetMapping("/students")
    public ResponseEntity<Page<User>> getAllStudents(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String sortField,
            @RequestParam(required = false) String sortOrder) {
        
        // 检查当前用户是否为管理员或讲师
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> currentUserOpt = userService.getUserById(currentUserId);
        if (!currentUserOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        User currentUser = currentUserOpt.get();
        if (!"ADMIN".equals(currentUser.getRole()) && !"LECTURER".equals(currentUser.getRole())) {
            return ResponseEntity.status(403).build();
        }
        
        // 构建排序
        Sort sort = Sort.unsorted();
        if (sortField != null && !sortField.isEmpty()) {
            Sort.Direction direction = "DESC".equalsIgnoreCase(sortOrder) ? Sort.Direction.DESC : Sort.Direction.ASC;
            sort = Sort.by(direction, sortField);
        }
        
        Pageable pageable = PageRequest.of(page, size, sort);
        
        // 获取学生列表
        Page<User> students;
        if (keyword != null && !keyword.isEmpty()) {
            students = userService.searchStudents(keyword, pageable);
        } else {
            students = userService.getAllStudents(pageable);
        }
        
        return ResponseEntity.ok(students);
    }

    /**
     * 管理员调整用户积分
     */
    @PostMapping("/admin/adjust")
    public ResponseEntity<StudyPointsTransaction> adminAdjustPoints(
            @RequestBody Map<String, Object> request) {
        
        // 检查当前用户是否为管理员
        Long currentUserId = getCurrentUserId();
        if (currentUserId == null) {
            return ResponseEntity.status(401).build();
        }
        
        Optional<User> currentUserOpt = userService.getUserById(currentUserId);
        if (!currentUserOpt.isPresent()) {
            return ResponseEntity.status(401).build();
        }
        
        User currentUser = currentUserOpt.get();
        if (!"ADMIN".equals(currentUser.getRole())) {
            return ResponseEntity.status(403).build();
        }
        
        // 获取请求参数
        Long userId = ((Number) request.get("userId")).longValue();
        Integer points = ((Number) request.get("points")).intValue();
        String transactionType = (String) request.get("transactionType");
        String description = (String) request.get("description");
        
        // 调整积分
        Optional<User> targetUserOpt = userService.getUserById(userId);
        if (!targetUserOpt.isPresent()) {
            return ResponseEntity.badRequest().build();
        }
        
        User targetUser = targetUserOpt.get();
        StudyPointsTransaction transaction = pointsService.addPoints(targetUser, points, transactionType, description, null);
        return ResponseEntity.ok(transaction);
    }

    /**
     * 获取当前认证用户的ID
     */
    private Long getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.getPrincipal() instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            String username = userDetails.getUsername();
            return userService.getUserByUsername(username).map(User::getId).orElse(null);
        }
        return null;
    }

    /**
     * 转换StudyPointsTransaction到StudyPointsTransactionDto
     */
    private StudyPointsTransactionDto convertToTransactionDto(StudyPointsTransaction transaction) {
        StudyPointsTransactionDto dto = new StudyPointsTransactionDto();
        dto.setId(transaction.getId());
        if (transaction.getUser() != null) {
            dto.setUserId(transaction.getUser().getId());
            dto.setUserName(transaction.getUser().getName());
        }
        dto.setPoints(transaction.getPoints());
        dto.setTransactionType(transaction.getTransactionType());
        dto.setDescription(transaction.getDescription());
        dto.setReferenceId(transaction.getReferenceId());
        dto.setTransactionTime(transaction.getTransactionTime());
        return dto;
    }
}